package com.shinhye.elephantsafe;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shinhye.elephantsafe.domain.AppInfo;
import com.shinhye.elephantsafe.engine.AppInfomations;
import com.shinhye.elephantsafe.utils.DensityUtil;

public class AppManagerActivity extends Activity {
	private final String TAG = "AppManagerActivity";
	private List<AppInfo> appInfos;
	private List<AppInfo> userAppInfos;
	private List<AppInfo> sysAppInfos;
	private ListView lv_applist;
	private LinearLayout ll_loading;
	private TextView tv_subtitle;
	private PopupWindow popupWindow;
	private AppInfo appInfo;  //指示哪个app被点击了
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			ll_loading.setVisibility(View.GONE);
			tv_subtitle.setVisibility(View.VISIBLE);
			lv_applist.setVisibility(View.VISIBLE);
			lv_applist.setAdapter(new MyAppInfoAdpater());
		};
	};
	private TextView tv_romavail;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_appmanager);
		
		ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
		
		lv_applist = (ListView) findViewById(R.id.lv_applist);
		tv_subtitle = (TextView) findViewById(R.id.tv_subtitle);
		tv_romavail = (TextView) findViewById(R.id.tv_romavail);
		TextView tv_sdavail = (TextView) findViewById(R.id.tv_sdavail);
		tv_romavail.append(getAvailableSpace(Environment.getDataDirectory().getAbsolutePath()));
		tv_sdavail.append(getAvailableSpace(Environment.getExternalStorageDirectory().getAbsolutePath()));
		
		getData();
		
		//添加滚动监听器，从而设置当前滚动位置是系统软件还是用户软件
		lv_applist.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				dismissPopup();
				if(userAppInfos != null && sysAppInfos != null) {
					if(firstVisibleItem > userAppInfos.size()) {
						tv_subtitle.setText("系统软件(" + sysAppInfos.size() + ")");
					} else {
						tv_subtitle.setText("用户软件(" + userAppInfos.size() + ")");
					}
				}
			}
		});
		
		//用户点击Item时弹出菜单
		lv_applist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				dismissPopup();
				if(!(view instanceof RelativeLayout)) {
					return;
				}
				appInfo = (AppInfo) parent.getItemAtPosition(position);
				MyOnClickListener listener = new MyOnClickListener();

				View v = View.inflate(AppManagerActivity.this, R.layout.popup_applist_item, null);
				TextView tv_uninstall = (TextView) v.findViewById(R.id.tv_uninstall);
				TextView tv_start = (TextView) v.findViewById(R.id.tv_start);
				TextView tv_share = (TextView) v.findViewById(R.id.tv_share);
				tv_uninstall.setOnClickListener(listener);
				tv_start.setOnClickListener(listener);
				tv_share.setOnClickListener(listener);
				
				popupWindow = new PopupWindow(v, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
				popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
				int[] location = new int[2];
				view.getLocationInWindow(location);
				
				v.startAnimation(AnimationUtils.loadAnimation(AppManagerActivity.this, R.anim.popup_common_animset));
				
				int px = DensityUtil.dip2px(AppManagerActivity.this, 60);
				popupWindow.showAtLocation(lv_applist, Gravity.LEFT|Gravity.TOP, px, location[1]);
			}
		});
		
		//用户长按Item时
		lv_applist.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				dismissPopup();
				if(!(view instanceof RelativeLayout)) {
					return true;
				}
				appInfo = (AppInfo) parent.getItemAtPosition(position);
				android.app.AlertDialog.Builder builder = new AlertDialog.Builder(AppManagerActivity.this);
				builder.setIcon(appInfo.getIcon());
				builder.setTitle(appInfo.getName());
				String message = "程序包名：\n  " + appInfo.getPackName() + "\n安装位置： "
						+ (appInfo.isRom() ? "手机内存" : "SD卡") + "\nAPP总大小："
						+ formatter(appInfo.getAppsize()) + "\n缓存大小： "
						+ formatter(appInfo.getCachesize()) + "\n数据大小： "
						+ formatter(appInfo.getDatasize()) + "\n程序大小： "
						+ formatter(appInfo.getCodesize());
				builder.setMessage(message);
				builder.show();
				
				return true;
			}
		});
	}
	
	/**
	 * A implement for OnClickListener.
	 * @author ShinHye
	 *
	 */
	class MyOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			dismissPopup();
			switch(v.getId()) {
			case R.id.tv_uninstall:
				Log.i(TAG, "开始卸载程序！");
				uninstallApp();
				break;
			case R.id.tv_start:
				Log.i(TAG, "启动程序！");
				startApp();
				break;
			case R.id.tv_share:
				Log.i(TAG, "分享程序！");
				shareApp();
				break;
			}
		}
		
	}
	
	/**
	 * Share the specified App.
	 */
	public void shareApp() {
		// <action android:name="android.intent.action.SEND" />
		// <category android:name="android.intent.category.DEFAULT" />
		// <data android:mimeType="text/plain" />
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		String text = "推荐你一款好软件："
				+ appInfo.getName()
				+ "。赶快来应用市场下载吧！地址：https://play.google.com/store/apps/details?id="
				+ appInfo.getPackName();
		intent.putExtra(Intent.EXTRA_TEXT, text);
		startActivity(intent);
	}

	/**
	 * Start the specified App.
	 */
	public void startApp() {
		Intent intent = new Intent();
		String packName = appInfo.getPackName();
		PackageManager pm = getPackageManager();
		intent = pm.getLaunchIntentForPackage(packName);
		if(intent != null) {
			startActivity(intent);
		} else {
			Toast.makeText(this, "这个应用程序无法直接打开！", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Uninstall the specified App.
	 */
	public void uninstallApp() {
		if(appInfo.isUser()) {
			Intent intent = new Intent(Intent.ACTION_DELETE);
			intent.setData(Uri.parse("package:" + appInfo.getPackName()));
			startActivityForResult(intent, 101);
		} else {
			Toast.makeText(this, "系统应用无法卸载！", Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 101) {
			//TODO -5- 卸载的resultCode成功失败都是0怎么解决？
			getData();
			
			tv_romavail.setText("内存可用：" + getAvailableSpace(Environment.getDataDirectory().getAbsolutePath()));
		}
	}

	/**
	 * Start a new thread to update UI while loading a lot of data.
	 */
	public void getData() {
		lv_applist.setVisibility(View.INVISIBLE);
		ll_loading.setVisibility(View.VISIBLE);
		tv_subtitle.setVisibility(View.INVISIBLE);
		//费时的操作要放在子线程中
		new Thread(new Runnable() {
			@Override
			public void run() {
				
				appInfos = new AppInfomations().getAllAppInfos(AppManagerActivity.this);
				userAppInfos = new ArrayList<AppInfo>();
				sysAppInfos = new ArrayList<AppInfo>();
				for(AppInfo info : appInfos) {
					if(info.isUser())
						userAppInfos.add(info);
					else
						sysAppInfos.add(info);
				}
				
				handler.sendEmptyMessage(0);
			}
		}).start();
	}
	
	/**
	 * Dismiss the specified PopupWindow.
	 */
	public void dismissPopup() {
		if(popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
		}
	}
	
	/**
	 * A adapter to provider data for ListView.
	 * @author ShinHye
	 *
	 */
	class MyAppInfoAdpater extends BaseAdapter {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			ViewHolder holder;
			AppInfo info;
			if(position == 0) {
				TextView tv_user = new TextView(AppManagerActivity.this);
				tv_user.setTextColor(Color.WHITE);
				tv_user.setBackgroundColor(0xFF666666);
				tv_user.setPadding(2, 0, 0, 0);
				tv_user.setTextSize(16);
				tv_user.setText("用户软件(" + userAppInfos.size() + ")");
				return tv_user;
			} else if(position == userAppInfos.size() + 1) {
				TextView tv_sys = new TextView(AppManagerActivity.this);
				tv_sys.setTextColor(Color.WHITE);
				tv_sys.setBackgroundColor(0xFF666666);
				tv_sys.setPadding(2, 0, 0, 0);
				tv_sys.setTextSize(16);
				tv_sys.setText("系统软件(" + sysAppInfos.size() + ")");
				return tv_sys;
			} else if(position < userAppInfos.size() + 1) {
				info = userAppInfos.get(position - 1);
			} else {
				int newPos = position - 1 - userAppInfos.size() - 1;
				info = sysAppInfos.get(newPos);
			}
			if(convertView != null && convertView instanceof RelativeLayout) {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			} else {
				view = View.inflate(AppManagerActivity.this, R.layout.item_appinfolist, null);
				holder = new ViewHolder();
				holder.iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
				holder.tv_appname = (TextView) view.findViewById(R.id.tv_appname);
				holder.tv_romorsd = (TextView) view.findViewById(R.id.tv_romorsd);
				holder.tv_appspace = (TextView) view.findViewById(R.id.tv_appspace);
				view.setTag(holder);
			}
			
			holder.iv_icon.setImageDrawable(info.getIcon());
			holder.tv_appname.setText(info.getName());
			if(info.isRom()) {
				holder.tv_romorsd.setText("手机内存");
			} else {
				holder.tv_romorsd.setText("外部存储");
			}
			holder.tv_appspace.setText(formatter(info.getAppsize()));
			
			return view;
		}
		
		@Override
		public int getCount() {
			return userAppInfos.size() + 1 + sysAppInfos.size() + 1;
		}

		@Override
		public Object getItem(int position) {
			AppInfo appInfo;
			if(position == 0) {
				return null;
			} else if(position == userAppInfos.size() + 1) {
				return null;
			} else if(position < userAppInfos.size() + 1) {
				appInfo = userAppInfos.get(position - 1);
			} else {
				int newPos = position - 1 - userAppInfos.size() - 1;
				appInfo = sysAppInfos.get(newPos);
			}
			return appInfo;
		}
		
		@Override
		public long getItemId(int position) {
			return 0;
		}
	}
	
	static class ViewHolder {
		ImageView iv_icon;
		TextView tv_appname;
		TextView tv_romorsd;
		TextView tv_appspace;
	}
	
	/**
	 * Get formatted available space of a given path.  
	 * @param path The path you want to get file-system info
	 * @return Available space in this path
	 */
	@SuppressWarnings("deprecation")
	public String getAvailableSpace(String path) {
		StatFs sf = new StatFs(path);
		long blocks = sf.getAvailableBlocks();
		long size = sf.getBlockSize();
		
		return formatter(blocks * size);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		dismissPopup();
	}
	
	/**
	 * Get a formatted number.
	 * @param number The original number.
	 * @return A formatted number. 
	 */
	public String formatter(long number) {
		return Formatter.formatFileSize(this, number);
	}
}
